
package com.gitee.jmash.rbac.service;

import java.util.List;
import java.util.UUID;
import com.gitee.jmash.core.orm.DtoPage;
import com.gitee.jmash.core.orm.DtoTotal;
import com.gitee.jmash.core.orm.cdi.JpaTenantService;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.core.orm.tenant.TenantService;
import com.gitee.jmash.core.transaction.JakartaTransaction;
import com.gitee.jmash.rbac.dao.ModuleDao;
import com.gitee.jmash.rbac.dao.ResourceDao;
import com.gitee.jmash.rbac.entity.ModuleEntity;
import jakarta.enterprise.inject.Typed;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional.TxType;
import jakarta.validation.executable.ValidateOnExecution;
import jmash.rbac.protobuf.ModuleReq;

/**
 * 系统模块 rbac_module读服务.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
@Typed(ModuleRead.class)
@Transactional(TxType.SUPPORTS)
@JpaTenantService
@ValidateOnExecution
public class ModuleReadBean implements ModuleRead, JakartaTransaction {

  protected TenantEntityManager tem = new TenantEntityManager();

  protected ModuleDao moduleDao = new ModuleDao(this.tem);
  protected ResourceDao resourceDao = new ResourceDao(this.tem);

  @PersistenceContext(unitName = "ReadRbac")
  public void setEntityManager(EntityManager entityManager) {
    this.tem.setEntityManager(entityManager, false);
  }

  @Override
  @SuppressWarnings("unchecked")
  public <T extends TenantService> T setTenant(String tenant) {
    this.tem.setTenant(tenant);
    return (T) this;
  }

  @Override
  public EntityManager getEntityManager() {
    return this.tem.getEntityManager();
  }

  @Override
  public void setTenantOnly(String tenant) {
    this.tem.setTenantOnly(tenant);
  }
  
  @Override
  public String getTenant() {
    return this.tem.getTenant();
  }

  @Override
  public ModuleEntity findById(UUID entityId) {
    return moduleDao.find(entityId);
  }

  @Override
  public DtoPage<ModuleEntity, DtoTotal> findPageByReq(ModuleReq req) {
    return moduleDao.findPageByReq(req);
  }

  @Override
  public List<ModuleEntity> findListByReq(ModuleReq req) {
    return moduleDao.findListByReq(req);
  }

  @Override
  public boolean checkModuleCodeUnique(String moduleCode) {
    List<ModuleEntity> moduleList = moduleDao.findListByReq(ModuleReq.newBuilder().setModuleCode(moduleCode).build());
    if(moduleList.size() > 0) {
      return true;
    }
    return false;
  }

  @Override
  public void close() throws Exception {
    CDI.current().destroy(this);
  }
}
